/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pnt.server;

/**
 * SINGLETON
 * 
 * The server object listens on th
 * 
 * @author andrew
 */
import java.util.logging.Logger;

public class Server {
    
    @SuppressWarnings("unused")
	private static Logger logger = Logger.getLogger("pnt.server"); 
    
    ConnectionManager conMan;
    
    TCPConnectionListener PrimaryTCPListener;
    UDPListener udpListener;

    TCPConnectionListener[] TCPHelpers;
    Thread[] TCPHelperThreads;
    
    Thread tcpThread;
    Thread udpThread;
    
    public static int DEFAULT_PORT = 1234;
    static final int MAX_HELPERS = 10;
    
    public static Server instance;
    
    public static Server getServer(){
        if (instance == null)
            instance = new Server();
        return instance;
    }
    
    private Server(){
        
        if (instance != null)
            throw new Error("Server already initialised.");
        
        conMan = new ConnectionManager();
        
        PrimaryTCPListener = new TCPConnectionListener(DEFAULT_PORT, conMan, false);
        udpListener = new UDPListener(DEFAULT_PORT, conMan);

        tcpThread = new Thread(PrimaryTCPListener);
        udpThread = new Thread(udpListener);
        
        TCPHelpers = new TCPConnectionListener[MAX_HELPERS];
        TCPHelperThreads = new Thread[MAX_HELPERS];
    }

    public void run(){
        tcpThread.start();
        udpThread.start();
        conMan.run();
    }

    public boolean terminate(){
        instance = null;
        conMan.stop();
        
        boolean helperResults = true;
        
        for (TCPConnectionListener t : TCPHelpers)
            helperResults = helperResults && t.stop();
        
        return (PrimaryTCPListener.stop() && udpListener.stop() && helperResults);
    }

    public TCPConnectionListener[] getTCPHelpers(int numOfHelpers){
        
        if(numOfHelpers > MAX_HELPERS) numOfHelpers = MAX_HELPERS;
        
        TCPConnectionListener[] helpers = new TCPConnectionListener[numOfHelpers];
        
        // check to see if helper already exists. If not then initialise.
        for (int i = 0; i < numOfHelpers; i++){
            if(TCPHelpers[i] == null){
                TCPHelpers[i] = new TCPConnectionListener(0, conMan, true);
                TCPHelperThreads[i] = new Thread(TCPHelpers[i]);
                TCPHelperThreads[i].start();
            }
            helpers[i] = TCPHelpers[i];
        }
        
        return helpers;
    }

}
